package top.h1234.codesandbox.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import top.h1234.codesandbox.JavaDockerCodeSandbox;
import top.h1234.codesandbox.JavaNativeCodeSandbox;
import top.h1234.codesandbox.model.ExecuteCodeRequest;
import top.h1234.codesandbox.model.ExecuteCodeResponse;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
public class MainController {

    @Resource
    private JavaNativeCodeSandbox javaNativeCodeSandbox;

    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;

    // 定义鉴权请求头和密钥
    private static final String AUTH_REQUEST_HEADER = "auth";
    private static final String AUTH_REQUEST_SECRET = "hyr";

    /**
     * 执行代码
     *
     * @param executeCodeRequest 执行代码的请求体
     * @return 执行代码的响应体
     */
    @PostMapping("/executeCode")
    ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest, HttpServletRequest request, HttpServletResponse response) {
        // 获取调用方传输的请求头信息
        String authHeader = request.getHeader(AUTH_REQUEST_HEADER);
        // 验证请求头中的密钥是否和我们定义的密钥一致
        if (!AUTH_REQUEST_SECRET.equals(authHeader)) {
            response.setStatus(403);
            return null;
        }
        if (executeCodeRequest == null) throw new RuntimeException("请求参数不存在");
        return javaDockerCodeSandbox.executeCode(executeCodeRequest);
    }
}
